package com.seecen.cywbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.cywbackend.Exception.BusinessException;
import com.seecen.cywbackend.config.SensitiveFilter;
import com.seecen.cywbackend.mapper.DynamicMapper;
import com.seecen.cywbackend.mapper.LikeMapper;
import com.seecen.cywbackend.mapper.UserMapper;
import com.seecen.cywbackend.pojo.Comment;
import com.seecen.cywbackend.pojo.Dynamic;
import com.seecen.cywbackend.pojo.Like;
import com.seecen.cywbackend.pojo.User;
import com.seecen.cywbackend.pojo.vo.CommentDTO;
import com.seecen.cywbackend.pojo.vo.CommentVO;
import com.seecen.cywbackend.service.CommentService;
import com.seecen.cywbackend.mapper.CommentMapper;
import com.seecen.cywbackend.utils.PageResult;
import com.seecen.cywbackend.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【t_comment(评论表)】的数据库操作Service实现
* @createDate 2025-03-25 17:14:24
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private LikeMapper likeMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private SensitiveFilter sensitiveWordFilter;


    @Override
    public Result getComments(Integer dynamicId, Integer page, Integer size,Long userId) {
        Page<Comment> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        //优先按点赞数降序，再按创建时间降序
        wrapper.eq(Comment::getDynamicId, dynamicId)
                .isNull(Comment::getParentId)
                .orderByDesc(Comment::getLikeCount,Comment::getCreateTime);
        IPage<Comment> commentPage = commentMapper.selectPage(pageParam, wrapper);
        List<CommentVO> voList = commentPage.getRecords().stream().map(comment -> {
            CommentVO vo = convertToVO(comment);
            // 查询点赞状态...
            vo.setIsLiked(likeMapper.exists(new LambdaQueryWrapper<Like>()
                    .eq(Like::getUserId, userId)
                    .eq(Like::getTargetId, comment.getId())
                    .eq(Like::getTargetType, 2)));
            // 加载二级回复
            vo.setReplies(loadReplies(comment.getId(), userId));
            return vo;
        }).collect(Collectors.toList());

        PageResult<CommentVO> result = new PageResult<>(voList, commentPage.getTotal());
        return Result.ok(result);
    }

    private List<CommentVO> loadReplies(Integer parentId,Long userId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getParentId, parentId)
                .orderByDesc(Comment::getLikeCount,Comment::getCreateTime);
        //连同点赞状态
        List<CommentVO> res= commentMapper.selectList(wrapper).stream().map(comment -> {
            CommentVO vo = convertToVO(comment);
            vo.setIsLiked(likeMapper.exists(new LambdaQueryWrapper<Like>()
                    .eq(Like::getUserId, userId)
                    .eq(Like::getTargetId, comment.getId())
                    .eq(Like::getTargetType, 2)));
            return vo;
        }).collect(Collectors.toList());
        return res;
    }

    private CommentVO convertToVO(Comment comment) {
        CommentVO vo = new CommentVO();
        BeanUtils.copyProperties(comment, vo);
        User user = userMapper.selectById(comment.getUserId());
        vo.setUserName(user.getNickname());
        vo.setUserAvatar(user.getAvatar());
        return vo;
    }

    @Override
    public Result createComment(Long userId, CommentDTO dto){
        // 1. 参数校验
        validateComment(dto);
        // 2. 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            try {
                throw new BusinessException("用户不存在");
            } catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }
        // 3. 构建评论实体
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setDynamicId(dto.getDynamicId());
        String content;
        if(dto.getReplyCommentId()!=null) content="@"+dto.getReplyUserName()+" "+dto.getContent();
        else content=dto.getContent();
        System.out.println("过滤前："+content);
        System.out.println("过滤后："+filterSensitiveWords(content));
        comment.setContent(filterSensitiveWords(content)); // 敏感词过滤
        comment.setParentId(dto.getParentId());
        comment.setReplyUserId(dto.getReplyUserId());
        comment.setCreateTime(new Date());
        // 4. 处理楼层计算（仅限一级评论）
        if (dto.getParentId() == null) {
            Integer maxFloor = commentMapper.selectMaxFloor(dto.getDynamicId());
            comment.setFloor(maxFloor != null ? maxFloor + 1 : 1);
        }
        // 5. 插入评论
        commentMapper.insert(comment);
        // 6. 更新动态评论数
        dynamicMapper.incrementCommentCount(dto.getDynamicId());
        return Result.ok(null);
    }

    private void validateComment(CommentDTO dto){
        // 校验动态是否存在
        Dynamic dynamic = dynamicMapper.selectById(dto.getDynamicId());
        if (dynamic == null || dynamic.getIsDeleted() == 1) {
            throw new BusinessException("动态不存在或已被删除");
        }
        // 校验父评论合法性
        if (dto.getParentId() != null) {
            Comment parent = commentMapper.selectById(dto.getParentId());
            if (parent == null || !parent.getDynamicId().equals(dto.getDynamicId())) {
                throw new BusinessException("回复的评论不存在");
            }
        }
        // 校验被回复用户存在
        if (dto.getReplyUserId() != null) {
            User replyUser = userMapper.selectById(dto.getReplyUserId());
            if (replyUser == null) {
                throw new BusinessException("被回复用户不存在");
            }
        }
    }

    // 敏感词过滤示例（需接入实际过滤服务）
    private String filterSensitiveWords(String content) {
        return sensitiveWordFilter.filter(content);
    }
}




